package com.quan.api.wx.oauth;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.bean.BeanUtil;
import com.quan.api.wx.vo.WxMpAuthVo;
import com.quan.commons.core.bean.R;
import com.quan.commons.core.biz.support.MyBaseController;
import com.quan.commons.core.configuration.WxMaConfiguration;
import com.quan.commons.core.properties.SystemValueProperties;
import com.quan.commons.core.utils.RedisUtils;
import com.quan.mall.commons.vo.UmsMemberVo;
import com.quan.mall.entity.FmsMemberWallet;
import com.quan.mall.entity.UmsMember;
import com.quan.mall.service.FmsMemberWalletService;
import com.quan.mall.service.FmsMemberWithdrawService;
import com.quan.mall.service.UmsMemberService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * 小程序授权登录
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/api/wx/mp")
public class ApiWxMpOAuthController extends MyBaseController {

    @Autowired
    private UmsMemberService umsMemberService;

    @Autowired
    private SystemValueProperties properties;

    @Autowired
    private FmsMemberWalletService fmsMemberWalletService;

    @Autowired
    private FmsMemberWithdrawService fmsMemberWithdrawService;


    /**
     * 授权登录获取用户信息
     *
     * @param vo
     * @return
     */
    @PostMapping(value = "/getUserInfo")
    public R getUserInfo(@RequestBody WxMpAuthVo vo) {
        try {
            // 根据appid来选择不同小程序
            WxMaService wxMaService = WxMaConfiguration.getMaService(vo.getAppid());


            // 微信登录code换取openid和SessionKey
            WxMaJscode2SessionResult sessionResult = wxMaService.getUserService().getSessionInfo(vo.getCode());

            // SessionKey
            String sessionKey = sessionResult.getSessionKey();

            // 解密用户信息
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, vo.getEncryptedData(), vo.getIv());


            // 根据OPENID查询数据库用户是否已存在
            UmsMemberVo memberVo = this.umsMemberService.getMemberByOpenId(userInfo.getOpenId());

            // 用户不存在则将用户信息保存到数据库
            if (null == memberVo) {
                memberVo = new UmsMemberVo();
                memberVo.setOpenid(userInfo.getOpenId());
                memberVo.setNickname(userInfo.getNickName());
                memberVo.setSex(Integer.parseInt(userInfo.getGender()));
                memberVo.setRegSrc(2);
                memberVo.setAvatar(userInfo.getAvatarUrl());
                this.umsMemberService.register(memberVo);
            }

            return R.ok().put("data", memberVo);

        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return R.failure("登录失败");
    }


    /**
     * 授权登录获取用户信息
     *
     * @param vo
     * @return
     */
    @PostMapping(value = "/bindOpenIdToMobile")
    public R bindOpenIdToMobile(@RequestBody WxMpAuthVo vo) {
        try {
            // 根据appid来选择不同小程序
            WxMaService wxMaService = WxMaConfiguration.getMaService(vo.getAppid());


            // 微信登录code换取openid和SessionKey
            WxMaJscode2SessionResult sessionResult = wxMaService.getUserService().getSessionInfo(vo.getCode());

            // SessionKey
            String sessionKey = sessionResult.getSessionKey();

            // 解密用户信息
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, vo.getEncryptedData(), vo.getIv());

            // 根据手机号查询数据库用户
            UmsMember member = this.umsMemberService.getMemberByMobile(vo.getMobile());

            if(null == member) {
                return R.failure("绑定失败：找不到该会员["+vo.getMobile()+"]");
            }

            // 将会员与openid绑定
            member.setOpenid(userInfo.getOpenId());

            this.umsMemberService.updateById(member);

            // 将openid保存到个人钱包
            FmsMemberWallet memberWallet = this.fmsMemberWalletService.getMemberWallter(member.getId());
            memberWallet.setOpenid(member.getOpenid());
            this.fmsMemberWalletService.updateById(memberWallet);

            return R.ok().put("data", member);

        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return R.failure("登录失败");
    }

    /**
     * 获取用户手机号
     *
     * @param vo
     * @return
     */
    @PostMapping("/getPhoneNumber")
    public Object getPhoneNumber(@RequestBody WxMpAuthVo vo) {
        try {
            WxMaService wxMaService = WxMaConfiguration.getMaService(vo.getAppid());

            // 微信登录code换取openid
            WxMaJscode2SessionResult sessionResult = wxMaService.getUserService().getSessionInfo(vo.getCode());

            // 解密获取用户手机号
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionResult.getSessionKey(), vo.getEncryptedData(), vo.getIv());

            return R.ok().put("data", phoneNoInfo);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return R.failure("获取手机号失败");
    }

}
